import React, { Component } from 'react'
import {
	Text, View, Animated, TouchableOpacity, StyleSheet, Dimensions
} from "react-native";
import { PageStatusIndex } from '../../../../../component/page-status/PageStatusIndex';
import { MorePage } from '../../../create/_components/MorePage';
import { SpaceBetween } from '../../../create/_components/SpaceBetween.js';
import { CURRENCY } from '../../../../../utils/helper';
import { CREDIT_TYPES } from '../../../../../config/definition';
import { API, API_GENERATE } from '../../../../../config/api';
import HTTP from '../../../../../utils/http'
import { style } from '../../../../../theme/style';
import MethodUtil from '../../../../../utils/MethodUtil';
import OrderApproveService from '../../_common/service';
import * as Animatable from 'react-native-animatable';
import ModalPicDelComponent from '../../../../../component/ModalPicDelComponent';
import ToastUtil from '../../../../../utils/toast';
const scale = GLOBAL.SCALE;
const screenWidth = Dimensions.get('window').width;

//基本信息
export class OrderBaseSection extends Component {
	constructor(props) {
		super(props);
		this.state = {
			data: {},
			status: 'loading',
			basicOnoff: true,
			resultModalVisible: false,
			loaded: false,
			lightBoxVisible: false,
			stateLightBoxData: false,
			profitList: [],
			isP: true,
			stateHeight: new Animated.Value(40),
			isHeight: false,
			trustList: {},
			trustData: {},
			companyInfo: {}
		}
	};

	componentWillReceiveProps (props) {
		let { trustData, companyInfo } = props || {};
		if (companyInfo && companyInfo.warehouseInfo) {
			this.setState({
				trustData,
				companyInfo,
				status: 'data'
			})
		}
	}

	// 基本信息  更多设置
	_startAnimated = () => {
		let { isHeight, stateHeight } = this.state;
		if (isHeight) {
			Animated.timing(stateHeight, { toValue: 40, duration: 300, }).start(() => { this.setState({ isHeight: false }) });
		} else {
			Animated.timing(stateHeight, { toValue: 290, duration: 300 }).start(() => { this.setState({ isHeight: true }) })
		}
	}
	_nameAfterType (orderType, sourceChannel) {
		return (
			<View style={{ flexDirection: 'row' }}>
				{orderType === 'P' ?
					<View style={[styles.orderType, { backgroundColor: '#F7B500' }]}>
						<Text style={{ fontSize: 11, color: '#FFF' }}>采</Text>
					</View> : null
				}
				{orderType === 'S' ?
					<View style={[styles.orderType, { backgroundColor: '#3E7406' }]}>
						<Text style={{ fontSize: 11, color: '#FFF' }}>销</Text>
					</View> : null
				}
				{sourceChannel === '2' ?
					<View style={[styles.orderType, { backgroundColor: '#E02020' }]}>
						<Text style={{ fontSize: 11, color: '#FFF' }}>壹化</Text>
					</View> : null
				}
			</View>
		)
	}
	async ChangeChoice (isP, data) {
		this.setState({
			isP,
			status: 'loading'
		})
		let { companyId, orderType, corpId } = data
		let trustSend = {
			companyId: companyId,
			corpType: orderType == 'P' ? '1' : '2',
			orderType: orderType
		}
		let companySend = {
			companyId: companyId,
			corpId: corpId,
			orderType: orderType
		}
		let trustData = await HTTP.POST(API_GENERATE(API.ORDER_TRUST_LIST), trustSend);
		let companyInfo = await HTTP.GET(API_GENERATE(API.COMPANY_ORDER_INFO), companySend);
		this.setState({
			trustData,
			companyInfo,
			status: 'data'
		})
	}

	baseInfoRef = ref => this.baseInfoView = ref;
	baseInfoSaleRef = ref => this.baseInfoSaleView = ref;

	render () {
		const { data, taskType, title, baseInfoType, propsData, choice } = this.props;
		let { basicOnoff, isP, trustData, companyInfo, status } = this.state;
		let baseInfo;
		let saleInfo = {};
		let purchaseInfo = {};
		var len = Math.ceil(screenWidth / 10);
		var arr = [];
		let warehouseInfo = {};
		let overDueInfo = {};
		for (let i = 0; i < len; i++) {
			arr.push(i);
		}
		/*
			* taskType  B-背靠背 L-领导 R-风控 F-财务
			* 如果是背靠背，根据传入的销售/采购类型，取对应基本信息
			* 背靠背的采购订单基本信息中的交货方式取销售基本信息中的交货方式（产品确定的）
		*/
		//是否为闭口
		if (data.bizMode === 1) {
			const { orderType, oppoOrderInfo } = data;
			oppoOrderInfo = oppoOrderInfo ? oppoOrderInfo : '';
			purchaseInfo = (orderType === 'P' ? data : oppoOrderInfo);//采购订单基本信息
			saleInfo = (orderType === 'P' ? oppoOrderInfo : data);//销售订单基本信息
			baseInfo = isP ? purchaseInfo : saleInfo;
		} else {
			baseInfo = data;
		}

		const { companyName, companyId, orderId, currency, orderType, sourceChannel, bizMode } = baseInfo;
		if (companyInfo && companyInfo.warehouseInfo) {
			warehouseInfo = companyInfo.warehouseInfo[0] || {}
			overDueInfo = companyInfo.overDueInfo[0] || {}
		}
		return (
			<View style={styles.itemBox}>
				<Animatable.View style={{ maxHeight: this.state.stateHeight, overflow: "hidden" }} >
					<View style={{ height: 60 }}>
						{companyName ?
							<View style={{ marginLeft: 20 }}>
								{bizMode !== 1 ?
									<View>
										<View style={styles.title}>
											<Text style={styles.itemTitle}>{companyName}</Text>
											{this._nameAfterType(orderType, sourceChannel)}
										</View>
										<TouchableOpacity
											onPress={() => propsData.navigation.navigate('OrderDetailsPage', {
												orderId: orderId,
												orderType: orderType,
												choice: choice
											})}>
											<Text style={styles.itemId}>{orderId} ></Text>
										</TouchableOpacity>
									</View> :
									<View style={{ flexDirection: 'row', alignItems: 'flex-start' }}>
										<TouchableOpacity onPress={() => this.ChangeChoice(true, purchaseInfo)}>
											<View style={styles.title}>
												<Text style={isP ? styles.itemTitle : styles.itemTitleUnSelect} numberOfLines={1}>{purchaseInfo.companyName}</Text>
												{isP ? this._nameAfterType('P', purchaseInfo.sourceChannel) : null}
											</View>
											{isP ?
												<TouchableOpacity
													onPress={() => propsData.navigation.navigate('OrderDetailsPage', {
														orderId: orderId,
														orderType: 'P',
														choice: choice
													})}>
													<Text style={styles.itemId}>{orderId} ></Text>
												</TouchableOpacity>
												: null
											}
										</TouchableOpacity>
										<Text style={styles.slash}>
											/
										</Text>
										<TouchableOpacity onPress={() => this.ChangeChoice(false, saleInfo)}>
											<View style={styles.title}>
												<Text style={isP ? styles.itemTitleUnSelect : styles.itemTitle} numberOfLines={1}>{saleInfo.companyName}</Text>
												{isP ? null : this._nameAfterType('S', saleInfo.sourceChannel)}
											</View>
											{!isP ?
												<TouchableOpacity
													onPress={() => propsData.navigation.navigate('OrderDetailsPage', {
														orderId: orderId,
														orderType: 'S',
														choice: choice
													})}>
													<Text style={styles.itemId}>{orderId} ></Text>
												</TouchableOpacity>
												: null
											}
										</TouchableOpacity>
									</View>
								}
							</View> : null
						}
					</View>
					{
						status == 'data' ?
							<View>
								<View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 5, marginLeft: 20, marginBottom: 20 }}>
									<Text style={{ fontSize: 12, color: '#FEFEFE', opacity: 1, marginRight: 10 }}>当前超期未执行出入库</Text>
									<Text style={{ fontSize: 13, color: '#FEFEFE' }}>{warehouseInfo.orderCnt}笔/ {warehouseInfo.quantity}吨</Text>
								</View>
								<View style={styles.dashLine}>
									{
										arr.map((item, index) => {
											return <Text style={styles.dashItem} key={'dash' + index}> </Text>
										})
									}
								</View>
								<View style={styles.overDue}>
									<Text style={{ fontSize: 12, color: '#FEFEFE' }}>近三个月
						<Text style={{ fontSize: 14, color: '#fff', fontWeight: '600' }}>{isP ? '采购' : '销售'}</Text>逾期情况</Text>
									<View style={styles.overDueItem}>
										<Text style={styles.overDueTitle}>逾期笔数/金额</Text>
										<Text style={styles.overDueText}>{overDueInfo.overdueCnt}笔 / {MethodUtil.toThousands(overDueInfo.overdueAmount || 0, 2)}元</Text>
									</View>
									<View style={[styles.overDueItem, { justifyContent: 'space-between' }]}>
										<View style={{ flexDirection: 'row', alignItems: 'center' }}>
											<Text style={styles.overDueTitle}>最长逾期</Text>
											<Text style={styles.overDueText}>{overDueInfo.overdueDay}天</Text>
										</View>
										<View style={{ flexDirection: 'row', alignItems: 'center' }}>
											<Text style={styles.overDueTitle}>当前是否有逾期</Text>
											<Text style={styles.overDueText}>{overDueInfo.isOverdue ? '逾期' : '未逾期'}</Text>
										</View>
									</View>
									{trustData && trustData.creditAmount ?
										<TouchableOpacity
											onPress={() => { propsData.navigation.navigate('BillPage', { "companyId": companyId, 'companyName': companyName, corpType: orderType === 'P' ? 1 : 0 }) }}>
											<View style={styles.creditBox}>
												<Text style={styles.credit}>授信额度: {
													MethodUtil.toThousands(trustData.creditAmount, 2)
													+ CURRENCY.getUnit(currency).text}，
									申请总占用 (包含本单) {
														MethodUtil.toThousands(trustData.usedAmount, 2)
														+ CURRENCY.getUnit(currency).text}，
									剩余可申请 {
														MethodUtil.toThousands(trustData.creditAmount - trustData.usedAmount, 2)
														+ CURRENCY.getUnit(currency).text}，
									有效期至 {trustData.creditEndDate}
													<Text style={{ color: '#0E7FFD' }}> >></Text>
												</Text>
											</View>
										</TouchableOpacity>
										: null}
								</View>
							</View>
							:
							<View style={{ height: 228, width: '100%' }}>
								<PageStatusIndex status='loading' />
							</View>
					}
				</Animatable.View>
				<MorePage onPressFn={() => { this._startAnimated() }} text={'查看近期交易'} />
			</View>
		)
	}
}
const styles = StyleSheet.create({
	itemBox: {
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		paddingBottom: 13 * scale,
		paddingTop: 10,
		backgroundColor: style.color.themeColor,
	},
	title: {
		flexDirection: 'row',
		alignItems: 'center'
	},
	itemTitle: {
		fontSize: 13,
		color: '#FEFEFE'
	},
	itemTitleUnSelect: {
		fontSize: 13,
		color: '#FEFEFE',
		opacity: 0.5,
		width: 100
	},
	slash: {
		marginHorizontal: 10,
		color: '#FEFEFE',
		fontSize: 28,
		// fontWeight: '600',
		marginTop: -15
	},
	orderType: {
		borderRadius: 2,
		paddingHorizontal: 4,
		paddingVertical: 2,
		marginLeft: 5
	},
	itemId: {
		marginTop: 7,
		fontSize: 12,
		color: '#FEFEFE'
	},
	dashLine: {
		flexDirection: 'row',
	},
	dashItem: {
		height: 1,
		width: 10,
		marginRight: 5,
		flex: 1,
		backgroundColor: '#C2C7D1',
		opacity: 0.48
	},
	overDue: {
		marginHorizontal: 20,
		marginVertical: 11
	},
	overDueItem: {
		marginTop: 14,
		flexDirection: 'row',
		alignItems: 'center'
	},
	overDueTitle: {
		fontSize: 12,
		color: '#FEFEFE',
	},
	overDueText: {
		marginLeft: 10,
		fontSize: 13,
		color: '#FEFEFE',
	},
	creditBox: {
		marginTop: 20,
		backgroundColor: "#fff",
		padding: 10,
		borderRadius: 6
	},
	credit: {
		fontSize: 11,
		lineHeight: 18
	}
})